import { ElMessage, ElMessageBox } from 'element-plus'
import moment from "moment";
// import * as echarts from 'echarts';
// import html2canvas from 'html2canvas'


function messageBox(text, type) {
  ElMessage({
    showClose: true,
    message: text,
    type: type,
    duration: 1000,
    // offset: 400
  });
}

const words = '零一二三四五六七八九'
const chinese = words.split('')

export default {
  // 提示
  success(text) { messageBox(text, 'success') },
  info(text) { messageBox(text, 'info') },
  warning(text) { messageBox(text, 'warning') },
  error(text) { messageBox(text, 'error') },
  confirm(option) {
    return new Promise((resolve, reject) => {
      let { content, type, title } = option
      ElMessageBox.confirm(content, title,
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type,
        }
      ).then(() => {
        resolve()
      })
        .catch(() => {
          reject()
        })
    })
  },

  copyText(text) {
    navigator.clipboard.writeText(text).then(() => {
      this.success('复制成功')
    })
  },


  goPath(name) {
    window.app.$router.push({
      path: '/' + name
    })
  },
  format(format) {
    var o = {
      "M+": this.getMonth() + 1, //month
      "d+": this.getDate(),    //day
      "h+": this.getHours(),   //hour
      "m+": this.getMinutes(), //minute
      "s+": this.getSeconds(), //second
      "q+": Math.floor((this.getMonth() + 3) / 3),  //quarter
      "S": this.getMilliseconds() //millisecond
    }
    if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
      (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o) if (new RegExp("(" + k + ")").test(format))
      format = format.replace(RegExp.$1,
        RegExp.$1.length == 1 ? o[k] :
          ("00" + o[k]).substr(("" + o[k]).length));
    return format;
  },
  arrayToTree(list, attr, root) {
    // // console.log(list, attr, root)
    function dataTree(list, root) {
      return list.filter(item => item[attr] === root).map(item => ({ ...item, children: dataTree(list, item.id) }))
    }
    return dataTree(list, root)
  },

  arrayToTree2(list, attr, attr2, root) {
    // // console.log(list, attr, root)
    function dataTree(list, root) {
      return list.filter(item => item[attr] === root).map(item => ({ ...item, children: dataTree(list, item[attr2]) }))
    }
    return dataTree(list, root)
  },

  // 是否在队列？
  isInArray(arr, value) {
    for (var i = 0; i < arr.length; i++) {
      if (value === arr[i].name) {
        return true;
      }
    }
    return false;
  },

  // 重排数组
  reSort(arr, str) {
    const sortBy = (property) => {
      return (value1, value2) => {
        const a = value1[property]
        const b = value2[property]
        return a < b ? 1 : a > b ? -1 : 0
      }
    }
    return arr.sort(sortBy(str)).reverse()
  },

  // 转化数字
  toggleNum(str) {
    let num = 0;
    if (str.length == 1) {
      if (str == "十") {
        num = 10;
      } else {
        num = this.backNum(str)
      }
    } else if (str.length == 2) {
      if (str[0] == "十") {
        num = 10 + this.backNum(str[1])
      } else if (str[1] == "十") {
        num = this.backNum(str[0]) * 10
      }
    } else if (str.length == 3) {
      num = this.backNum(str[0]) * 10 + this.backNum(str[2])
    }
    return num;
  },

  toggleCn(number) {
    if (number.match(/\D/) || number.length >= 14) return;
    let zhArray = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十']; // 数字对应中文
    let baseArray = ['', '十', '百', '千', '万', '十', '百', '千', '亿', '十', '百', '千', '万']; //进位填充字符，第一位是 个位，可省略
    let string = String(number).split('').reverse().map((item, index) => { // 把数字切割成数组并倒序排列，然后进行遍历转成中文
      // 如果当前位为0，直接输出数字， 否则输出 数字 + 进位填充字符
      item = Number(item) == 0 ? zhArray[Number(item)] : zhArray[Number(item)] + baseArray[index];
      return item;
    }).reverse().join(''); // 倒叙回来数组，拼接成字符串
    string = string.replace(/^一十/, '十');  // 如果以 一十 开头，可省略一
    string = string.replace(/零+/, '零');  // 如果有多位相邻的零，只写一个即可
    return string;
  },

  // 变回数字
  backNum(str) {
    let num = 0;
    chinese.map((x, y) => {
      if (str == x) {
        num = y
      }
    })
    return num;
  },

  // 数字转中文
  toggleChapter(num) {
    let str = ""
    if (num < 10) {
      str = chinese[num]
    } else if (num == 10) {
      str = "十";
    } else if (num > 10 && num < 20) {
      str = "十" + chinese[num - 10]
    } else if (num >= 20 && num < 100) {
      if (num % 10 == 0) {
        str = chinese[parseInt(num / 10)] + "十"
      } else {
        str = chinese[parseInt(num / 10)] + "十" + chinese[num % 10]
      }
    }
    return str;
  },

  // 生成图表
  initChart(chartDom, option) {
    let myChart = echarts.init(chartDom);
    option && myChart.setOption(option);
  },

  // 在哪个位置？
  jungleIndex(arr, value) {
    for (var i = 0; i < arr.length; i++) {
      if (value === arr[i].name) {
        return i;
      }
    }
  },

  //补零
  zero(num) {
    return num < 10 ? "0" + num : num
  },

  // 获得16进制
  toHex(d) {
    if (isNaN(d)) { d = 0 }
    var n = new Number(d).toString(16);
    return n.length == 1 ? '0' + n : n;
  },

  //随机数
  randomNumber(num) {
    return parseInt(Math.random() * num)
  },

  // 两数之间的随机数
  randomNum(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
  },

  //阿里云图标1
  setIconfont(obj, ico) {
    obj.innerHTML = `<span class="iconfont">` + '&#xe' + ico + `</span>`;
  },

  //阿里云图标2
  setIco(ico) {
    return "&#xe" + ico;
  },

  sortBy(field) {
    return (x, y) => {
      return x[field] - y[field]
    }
  },

  splitFormatData(arr, key) {
    const map = {}
    const res = []
    for (let i = 0; i < arr.length; i++) {
      const ai = arr[i]
      if (!map[ai[key]]) {
        map[ai[key]] = [ai]
      } else {
        map[ai[key]].push(ai)
      }
    }
    Object.keys(map).forEach(key => {
      if (key === undefined || key === 'undefined') {
        res.push({
          name: '未知',
          list: map[key]
        })
      } else {
        res.push({
          name: key,
          list: map[key]
        })
      }
    })
    return res
  },

  // 时间格式
  formatTime(time) {
    let m = 0,
      s = parseInt(time);
    if (s > 60) {
      m = parseInt(s / 60);
      s = parseInt(s % 60);
    }
    return this.zero(m) + ":" + this.zero(s);
  },

  formatDate(currentDate) {
    return moment(currentDate).format("YYYY-MM-DD");
  },

  formatDataTime(currentDate) {
    return moment(currentDate).format("YYYY-MM-DD  HH:mm:ss");
  },

  // 时间格式
  formatCur(time) {
    let m = parseInt(time.split(':')[0]);
    let s = parseInt(time.split(':')[1]);
    return m * 60 + s;
  },

  priceToChinese(n) {
    if (!/^(0|[1-9]\d*)(\.\d+)?$/.test(n)) {
      return "数据非法";  //判断数据是否大于0
    }
    var unit = "千百拾亿千百拾万千百拾元角分", str = "";
    n += "00";
    var indexpoint = n.indexOf('.');  // 如果是小数，截取小数点前面的位数
    if (indexpoint >= 0) {
      n = n.substring(0, indexpoint) + n.substr(indexpoint + 1, 2);   // 若为小数，截取需要使用的unit单位
    }
    unit = unit.substr(unit.length - n.length);  // 若为整数，截取需要使用的unit单位
    for (var i = 0; i < n.length; i++) {
      str += "零壹贰叁肆伍陆柒捌玖".charAt(n.charAt(i)) + unit.charAt(i);  //遍历转化为大写的数字
    }
    return str.replace(/零(千|百|拾|角)/g, "零").replace(/(零)+/g, "零").replace(/零(万|亿|元)/g, "$1")
      .replace(/(亿)万|壹(拾)/g, "$1$2").replace(/^元零?|零分/g, "").replace(/元$/g, "元整"); // 替换掉数字里面的零字符，得到结果
  },

  randomColor() {
    let color = 'rgb'
    let arr = []
    for (let i = 0; i < 3; i++) {
      arr.push(Math.floor(Math.random() * 255))
    }
    return color + '(' + arr.join(',') + ')'
  },

  // 日期你格式
  formatDate(y, m, d) {
    let str = y + "-" + this.zero(m) + "-" + this.zero(d);
    return str;
  },

  //设置时间
  setDate(date) {
    let y = date.getFullYear();
    let m = date.getMonth() + 1;
    let d = date.getDate();
    let time = this.formatDate(y, m, d);
    return time;
  },

  // 今天
  getDate() {
    let oDate = new Date();
    return this.setDate(oDate);
  },

  // 标准时间
  getTime() {
    let oDate = new Date();
    let time = this.zero(oDate.getHours()) + ":" +
      this.zero(oDate.getMinutes()) + ":" +
      this.zero(oDate.getSeconds())
    return time;
  },

  // 创建时间
  createTime() {
    let oDate = new Date();
    return this.setDate(oDate) + " " + this.getTime();
  },

  fileName(name) {
    let date = new Date();
    let y = date.getFullYear();
    let m = this.zero(date.getMonth() + 1);
    let d = this.zero(date.getDate());
    let h = this.zero(date.getHours());
    let mi = this.zero(date.getMinutes());
    let s = this.zero(date.getSeconds());
    return name + '' + y + m + d + h + mi + s
  },

  // 默认图片名称
  setImgName() {
    const date = new Date()
    return date.getFullYear() + this.zero(date.getMonth() + 1) +
      this.zero(date.getDate()) + this.zero(date.getHours()) +
      this.zero(date.getMinutes()) + this.zero(date.getSeconds())
  },

  // 文件下载
  fileDownload(downloadUrl, name) {
    const aLink = document.createElement('a')
    aLink.style.display = 'none'
    aLink.href = downloadUrl
    aLink.download = name
    // 触发点击-然后移除
    document.body.appendChild(aLink)
    aLink.click()
    document.body.removeChild(aLink)
  },

  // 打印图片
  oneImgExport(id, name) {
    let picName = ''
    if (name) {
      picName = name
    } else {
      picName = this.setImgName()
    }
    html2canvas(document.getElementById(id), {
      backgroundColor: '#fff'
    }).then((canvas) => {
      this.fileDownload(canvas.toDataURL('image/png'), picName)
    })
  },

  printOption(id, fn) {
    return {
      id,
      popTitle: '', // 打印配置页上方的标题
      extraHead: '', // 最上方的头部文字，附加在head标签上的额外标签，使用逗号分割
      preview: false, // 是否启动预览模式，默认是false
      previewTitle: '预览效果', // 打印预览的标题
      previewPrintBtnLabel: '预览结束，开始打印', // 打印预览的标题下方的按钮文本，点击可进入打印
      zIndex: 20002, // 预览窗口的z-index，默认是20002，最好比默认值更高
      previewBeforeOpenCallback() { }, // 预览窗口打开之前的callback
      previewOpenCallback() { }, // 预览窗口打开时的callback
      beforeOpenCallback() { }, // 开始打印之前的callback
      openCallback() { }, // 调用打印时的callback
      closeCallback() { }, // 关闭打印的callback(无法区分确认or取消)
      clickMounted() {
        if (fn) {
          fn()
        }
      },
      standard: '',
      extarCss: ''
    }
  },

  // 复制
  copy(obj) {
    obj.select();
    document.execCommand('Copy');
    alert('已复制好，可贴粘。');
  },

  // 按键
  keyDown(obj, callback) {
    obj.onkeydown = function (e) {
      if (callback) {
        callback(e.code)
      }
    }
  },

  // 数组分组
  group(arr, start, end) {
    let newArr = [];
    for (let i = start; i < end; i++) {
      newArr.push(arr[i])
    }
    return newArr
  },

  // 分割数组
  splitArr(arr, count) {
    var result = [];
    for (var i = 0, len = arr.length; i < len; i += count) {
      result.push(arr.slice(i, i + count));
    }
    return result;
  },

  // 区域拖拽
  limitDrag(obj, start, end) {
    /* obj = {bar,box,limit}*/
    obj.bar.onmousedown = function (ev) {
      let oEvent = ev || event;
      let disX = oEvent.clientX - obj.box.offsetLeft;
      let disY = oEvent.clientY - obj.box.offsetTop;
      document.onmousemove = function (ev) {
        let oEvent = ev || event;
        /*限制条件*/
        let l = oEvent.clientX - disX;
        let t = oEvent.clientY - disY;
        let w = obj.box.offsetWidth;
        let h = obj.box.offsetHeight;
        let r = obj.limit.offsetWidth;
        let b = obj.limit.offsetHeight;
        if (l < 0) {
          l = 0;
        } else if (l >= r - w) {
          l = r - w;
        }
        if (t < 0) {
          t = 0;
        } else if (t >= b - h) {
          t = b - h;
        }
        start(l, t)
      };
      document.onmouseup = function () {
        document.onmousemove = document.onmouseup = null;
        if (end) {
          end();
        }
      }
    }
  },

  // 横向拖拽
  progress(obj, start, end) {
    obj.bar.onmousedown = function (ev) {
      let oEvent = ev || event;
      let disX = oEvent.clientX - obj.bar.offsetLeft;
      document.onmousemove = function (ev) {
        let oEvent = ev || event;
        let l = oEvent.clientX - disX;
        let w = obj.bar.offsetWidth;
        let r = obj.limit.offsetWidth;
        if (l < 0) {
          l = 0;
        } else if (l >= r - w) {
          l = r - w;
        }
        start(l);
      };
      document.onmouseup = function () {
        document.onmousemove = document.onmouseup = null;
        if (end) {
          end();
        }
      }
    }
  },

  // 纵向拖拽
  dragPortrait(obj, start, end) {
    obj.bar.onmousedown = function (ev) {
      let oEvent = ev || event;
      let disY = oEvent.clientY - obj.bar.offsetTop;
      document.onmousemove = function (ev) {
        let oEvent = ev || event;
        let t = oEvent.clientY - disY;
        let b = obj.limit.offsetHeight;
        if (t < 0) {
          t = 0;
        } else if (t >= b) {
          t = b
        }
        start(t);
      };
      document.onmouseup = function () {
        document.onmousemove = document.onmouseup = null;
        if (end) {
          end();
        }
      }
    }
  },
  searchSql(option) {
    const { table, param, likes, keys, special, reverse } = option
    // // console.log(option)
    let sql = ''
    let page = 0, show = 10
    let condition = ' '
    let vague = ' '
    let displays = '*'
    if (param) {
      if (param.page) {
        page = param.page
      }
      if (param.show) {
        show = param.show
      }

      for (let i in param) {
        if (i != 'show' && i != 'page') {
          if (param[i] != '-1') {
            condition += ' AND ' + i + '=' + param[i]
          }
        }
      }
    }

    // 模糊搜索
    if (likes) {
      let attr = ''
      let value = ''
      for (let i in likes) {
        attr += '`' + i + '`,'
        value = likes[i]
      }
      attr = attr.slice(0, attr.length - 1)
      vague = 'AND CONCAT( ' + attr + ") LIKE '%" + value + "%'"
    }

    // 特殊
    if (special) {
      condition += ' AND ' + special
    }

    // 倒序
    if (reverse == true) {
      condition += ' ORDER BY id DESC'
    }
    // 显示字段
    if (keys) {
      displays = keys.join(',')
    }
    let base = `SELECT ${displays} from ${table} WHERE delid=1`
    let limit = ' LIMIT ' + (Number(page) - 1) * Number(page) + ',' + Number(show)
    sql = base + condition + vague + limit
    // // console.log(sql)
    return sql
  }
}
